<template>
  <div class="ChildPage TablePage" v-loading="loading">
    <vb-page ref="page">
      <template  #headerSearch-btn-append="{ searchForm }">
        <el-button type="success" size="small" icon="el-icon-download" @click="doDownload(searchForm)">导出采购订单</el-button>
      </template>
      <template #headerSearch-prepend="scope">
        <el-button size="small" v-loading="purOrderLoading" @click="reloadPurOrder? getPurOrderReloadResult(true): doPurOrderSync()" :icon="reloadPurOrder? 'el-icon-loading': 'el-icon-refresh'">{{ reloadPurOrder? '同步中，点击刷新': '同步采购订单' }}</el-button>
        <div style="flex-grow: 1; width: 100%;"></div>
      </template>
      <template #headerSearch-append="scope">
        <div class="cond">
          <scan class="label">供应商</scan>
          <el-select filterable remote :remote-method="e => getSupplierList(e)" v-model="scope.searchForm.supplierNo" size="small" clearable placeholder="请输入编码或者名称">
            <el-option v-for="item in supplierList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName" :value="item.fNumber" />
          </el-select>
        </div>
        <div class="cond">
          <scan class="label">物料</scan>
          <el-select filterable remote :remote-method="e => getMaterialList(e)" v-model="scope.searchForm.materialNo" size="small" clearable placeholder="请输入编码或者名称">
            <el-option v-for="item in materialList" :key="item.fNumber" :label="item.fNumber + '：' + item.fName + ' ' + item.fSpecification" :value="item.fNumber" />
          </el-select>
        </div>
      </template>
      <template #table-status="scope">
        <el-tag :type="scope.row.status === 'save'? 'info': 'success'">{{ scope.row.status === 'save'? '保存': '审核' }}</el-tag>
      </template>
      <template #table-handle-edit="scope">
        <el-button type="text" :icon="scope.row.status === 'save'? 'el-icon-edit': 'el-icon-view'" @click="gotoDetail(scope.row.orderNo)">{{ scope.row.status === 'save'? '编辑': '查看' }}</el-button>
      </template>
      <template #table-handle-audit="scope">
        <el-button type="text" icon="el-icon-s-promotion" @click="doPromotion(scope.row)" :style="scope.row.status === 'save'? '': 'color: var(--el-color-warning)'">{{ scope.row.status === 'save'? '审核': '反审' }}</el-button>
      </template>
      <template #table-handle-delete="scope">
        <el-button v-if="scope.row.status === 'save'" type="text" icon="el-icon-delete" @click="doDelete(scope.row)" style="color: var(--el-color-danger)">删除</el-button>
        <span v-else></span>
      </template>
      <template #table-handle-prepend="scope">
        <el-button  type="text" style="color:var(--el-color-success)" icon="el-icon-share" @click="toExport(scope.row.orderNo)">导出</el-button>
      </template>
    </vb-page>
  </div>
</template>

<script setup>

import { getCurrentInstance, ref } from 'vue'
const { proxy } = getCurrentInstance()

const loading = ref(false)
const purOrderLoading = ref(false)
const reloadPurOrder = ref(false)
const supplierLoading = ref(false)
const materialLoading = ref(false)
const reloadMaterial = ref(false)
const supplierList = ref([])
const materialList = ref([])
const reloadPurOrderRes = ref()
const reloadPurOrderMsg = ref()
const reloadPurOrderStartTime = ref()
const reloadPurOrderEndTime = ref()
const page = ref()

/**
 * 获取加载按钮的加载中状态
 */
const getPurOrderReloadResult = async showMsg => {
  purOrderLoading.value = true
  try {
    let res = await proxy.callApi("get_kingdee_pur_order")
    if (!res.res) return
    reloadPurOrder.value = res.reloadPurOrder
    reloadPurOrderRes.value = res.reloadPurOrderRes
    reloadPurOrderMsg.value = res.reloadPurOrderMsg
    reloadPurOrderStartTime.value = res.reloadPurOrderStartTime
    reloadPurOrderEndTime.value = res.reloadPurOrderEndTime
    if (showMsg) {
      if (reloadPurOrder.value) {
        proxy.$message.info('物料数据同步中')
      } else {
        if (reloadPurOrderRes.value) {
          page.value.reload()
          proxy.$message.success('已同步完成, 请刷新查看最新结果')
        } else {
          proxy.$message.error('同步失败，' + reloadPurOrderMsg.value)
        }
      }
    }
  } finally {
    purOrderLoading.value = false
  }
}

/**
 * 同步物料
 * */
const doPurOrderSync = async () => {
  try {
    let msg = '';
    if (reloadPurOrderStartTime.value) {
      msg += `<span style="font-weight: bold;">同步采购订单，耗时较长，是否继续执行？</span><br />
          前次同步${ reloadPurOrderRes.value? '成功!': `<span style="color: var(--danger)">失败!</span>` } ${ reloadPurOrderEndTime.value }
          ${ reloadPurOrderRes.value? '': `<br />${ reloadPurOrderMsg.value }` }
          <br />`;
    } else {
      msg = '同步采购订单，耗时较长，是否继续执行？';
    }
    await proxy.$confirm(msg, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: true
    })
  } catch(e) {
    return
  }
  try {
    loading.value = true
    let res = await proxy.callApi("sync_pur_order")
    if (!res.res) return
    reloadPurOrder.value = true
    proxy.$message.success('已经开始同步')
  } finally {
    loading.value = false
  }
}


/**
 * 跳转详细
 */
const gotoDetail = orderNo => {
  proxy.$router.push(`/purchase/purOrderDetail?orderNo=${ orderNo }`)
}
//跳转到打印
const toExport = orderNo =>{
  window.open(import.meta.env.VITE_EXPORT_URL + `purOrderExport?orderNo=${ orderNo}`)
}

const getSupplierList = async val => {
  if (!val) {
    supplierList.value = []
    return
  }
  supplierLoading.value = true
  try {
    const res = await proxy.callApi('get_supplier_by_key', { key: val, pageSize: 20 })
    if (!res.res) return
    supplierList.value = res.data
  } finally {
    supplierLoading.value = false
  }
}

/**
 * 获取物料列表
 */
const getMaterialList = async val => {
  if (!val) {
    materialList.value = []
    return
  }
  materialLoading.value = true
  try {
    const res = await proxy.callApi('get_material_list', { key: val, pageSize: 20 })
    if (!res.res) return
    materialList.value = res.data
  } finally {
    materialLoading.value = false
  }
}
/**
 * 审核或反审
 */
const doPromotion = async row => {
  loading.value = true
  try {
    if (row.status === 'save') {
      let res = await proxy.callApi('audit_pur_order', { orderNo: row.orderNo })
      if (!res.res) return
      row.status = 'audit'
      proxy.$message.success('审核完成!')
    } else {
      let res = await proxy.callApi('un_audit_pur_order', { orderNo: row.orderNo })
      if (!res.res) return
      row.status = 'save'
      proxy.$message.success('反审完成!')
    }
  } finally {
    loading.value = false
  }
}
const doDelete = async (row) => {
  try {
    await proxy.$confirm(`确定删除单据【${ row.orderNo }】吗`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
  } catch(e) {
    return
  }
  loading.value = true
  try {
    let res = await proxy.callApi('delete_pur_order', { orderNo: row.orderNo })
    if (!res.res) {
      return
    }
    proxy.$message.success(`已删除`)
    proxy.$refs.page.reload()
  } finally {
    loading.value = false
  }
}
const doDownload = async searchForm => {
  loading.value = true
  try {
    let res = await proxy.callApi('download_pur_order', searchForm)
    if (!res.res) {
      return
    }
    proxy.$message.success(`已下载`)
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.cond {
  display: flex;
  align-items: center;
  margin: 5px 10px 5px 0;
  border-radius: 4px;
  border: 1px solid #DCDFE6;
  .label {
    font-size: 12px;
    padding-left: 10px;
    color: var(--font-hb);
  }
  :deep(.el-input__inner) {
    width: 180px;
    border: 0;

  }
}
</style>
